package com.aabte.httpclient;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

public class MyCookiesForGet {

    private String baseUrl;
    private ResourceBundle bundle;
    private CookieStore store = new BasicCookieStore();

    @BeforeTest
    public void beforeTest(){
        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
    }

    @BeforeTest(dependsOnMethods = "beforeTest")
    public void setUrl(){
        baseUrl = bundle.getString("test.baseurl");
    }

    @Test
    public void testGetCookies() throws IOException {
        String result;
        // 拼接测试url
        String uri = bundle.getString("test.getCookies.uri");
        String testUrl = this.baseUrl + uri;
        HttpGet get = new HttpGet(testUrl);
        HttpClient client = HttpClients.custom().setDefaultCookieStore(store).build();
        HttpResponse httpResponse = client.execute(get);
        result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
        System.out.println(httpResponse.getStatusLine().getStatusCode());
        System.out.println(result);

        List<Cookie> cookies = store.getCookies();
        System.out.println(cookies.size());
        for (Cookie cookie :
                cookies) {
            System.out.println(cookie.getName() + " = " + cookie.getValue());
        }
    }

    @Test(dependsOnMethods = "testGetCookies")
    public void testGetWithCookies() throws IOException {
        String result;
        String uri = bundle.getString("test.getWithCookies.uri");
        String testUrl = this.baseUrl + uri;
        HttpGet get = new HttpGet(testUrl);
        HttpClient client = HttpClients.custom().setDefaultCookieStore(store).build();
        // 设置cookies信息
        HttpResponse httpResponse = client.execute(get);
        result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
        System.out.println(httpResponse.getStatusLine().getStatusCode());
        System.out.println(result);

        Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), 200);

    }

    public String getString(String key){
        return bundle.getString(key);
    }

    public Integer getInteger(String key){
        String result = bundle.getString(key);
        try {
            return Integer.valueOf(result);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return null;
        }
    }

}
